<template>
  <div class="video-page" v-if="hisDialog">
    <!--西药处方弹框 -->
    <el-dialog
      class="dialog-frame dialog-western"
      :visible.sync="hisDialog"
      @close="closeDialog('hisDialog')"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div slot="title" class="title-size">
        <div class="title-icon">
          <img src="@/assets/img/img_decorate.png" alt="" />
        </div>
        <span>his查询</span>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleActive">
        <el-tab-pane label="就诊信息" name="1"></el-tab-pane>
        <!-- <el-tab-pane label="门诊文件" name="2"></el-tab-pane> -->
        <el-tab-pane label="住院文件" name="3"></el-tab-pane>
      </el-tabs>
      <div v-show="activeName == 1">
        <div class="chatroom-drug-search">
          <!-- 就诊信息 -->
          <el-table
            class="l-table"
            :data="dataList"
            border
            max-height="300"
            highlight-current-row
          >
            <el-table-column prop="OrgName" label="机构名称">
              <template slot-scope="scope">
                <span>{{ scope.row.OrgName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Name" label="患者姓名">
              <template slot-scope="scope">
                <span>{{ scope.row.Name || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Sex" label="性别">
              <template slot-scope="scope">
                <span>{{ scope.row.Sex == 2 ? "女" : "男" || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="IdNum" label="证件号">
              <template slot-scope="scope">
                <span>{{ scope.row.IdNum || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="DoctName" label="就诊医生">
              <template slot-scope="scope">
                <span>{{ scope.row.DoctName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="DeptName" label="就诊科室">
              <template slot-scope="scope">
                <span>{{ scope.row.DeptName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="DiagnosisName" label="西医诊断">
              <template slot-scope="scope">
                <span>{{ scope.row.DiagnosisName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Birthday" label="出生日期">
              <template slot-scope="scope">
                <span>{{ scope.row.Birthday || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="PhoneNo" label="电话号码">
              <template slot-scope="scope">
                <span>{{ scope.row.PhoneNo || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="VisitTime" label="就诊时间">
              <template slot-scope="scope">
                <span>{{ scope.row.VisitTime || "-" }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="ExpenseTypeName" label="患者费别">
              <template slot-scope="scope">
                <span>{{ scope.row.ExpenseTypeName || "-" }} </span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="70" fixed="right">
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  @click="viewDetail(scope.row)"
                  >详情</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-show="activeName == 3">
        <div class="chatroom-drug-search">
          <!-- 就诊文件 -->
          <el-table
            class="l-table"
            :data="dataList"
            border
            max-height="300"
            highlight-current-row
          >
            <el-table-column prop="OrgName" label="机构名称">
              <template slot-scope="scope">
                <span>{{ scope.row.OrgName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="PatientName" label="患者姓名">
              <template slot-scope="scope">
                <span>{{ scope.row.PatientName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="PatientAge" label="患者年龄">
              <template slot-scope="scope">
                <span>{{ scope.row.PatientAge || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Sex" label="性别">
              <template slot-scope="scope">
                <span>{{ scope.row.Sex == 2 ? "女" : "男" || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="BedName" label="床位号">
              <template slot-scope="scope">
                <span>{{ scope.row.BedName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="DoctorName" label="主管医生">
              <template slot-scope="scope">
                <span>{{ scope.row.DoctorName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="DepartmentName" label="就诊科室">
              <template slot-scope="scope">
                <span>{{ scope.row.DepartmentName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Diagnosis" label="诊断">
              <template slot-scope="scope">
                <span>{{ scope.row.Diagnosis || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="NurseName" label="责任护士">
              <template slot-scope="scope">
                <span>{{ scope.row.NurseName || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Prepayment" label="预缴金总额">
              <template slot-scope="scope">
                <span>{{ scope.row.Prepayment || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="IdNum" label="证件号">
              <template slot-scope="scope">
                <span>{{ scope.row.IdNum || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="AreaNo" label="病区号">
              <template slot-scope="scope">
                <span>{{ scope.row.AreaNo || "-" }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="InpTimes" label="住院次数">
              <template slot-scope="scope">
                <span>{{ scope.row.InpTimes || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Birthday" label="出生日期">
              <template slot-scope="scope">
                <span>{{ scope.row.Birthday || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="Phone" label="电话号码">
              <template slot-scope="scope">
                <span>{{ scope.row.Phone || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="ExpCategory" label="患者费别">
              <template slot-scope="scope">
                <span>{{ scope.row.ExpCategory || "-" }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="TotalCost" label="费用总额">
              <template slot-scope="scope">
                <span>{{ scope.row.TotalCost || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="TotalDays" label="住院天数">
              <template slot-scope="scope">
                <span>{{ scope.row.TotalDays || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="InTime" label="住院时间">
              <template slot-scope="scope">
                <span>{{ scope.row.InTime || "-" }} </span>
              </template>
            </el-table-column>
            <el-table-column prop="OutTime" label="出院时间">
              <template slot-scope="scope">
                <span>{{ scope.row.OutTime || "-" }} </span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="70" fixed="right">
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  @click="viewFileDetail(scope.row)"
                  >详情</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <el-pagination
        style="text-align:center;margin:15px 25px;"
        @current-change="changePage"
        :current-page="dataPage.current"
        :page-size="dataPage.size"
        layout="prev, pager, next"
        :total="dataPage.total"
      >
      </el-pagination>
    </el-dialog>
    <!-- 就诊详情 -->
    <el-dialog
      custom-class="patient-detail-dialog"
      :visible.sync="patientDetailDialog"
    >
      <div slot="title" class="title-size">
        <span>就诊信息</span>
      </div>
      <div>
        <el-row :gutter="10">
          <el-col :span="12">
            <span>就诊日期：</span>
            <span>{{ patientDetail.VisitDate }}</span>
          </el-col>
          <el-col :span="12">
            <span>科别：</span>
            <span>{{ patientDetail.DeptName }}</span>
          </el-col>
          <el-col :span="12">
            <span>门诊号：</span>
            <span>{{ patientDetail.VisitId }}</span>
          </el-col>
          <el-col :span="12">
            <span>付款类型：</span>
            <span></span>
          </el-col>
          <el-col :span="12">
            <span>姓名：</span>
            <span>{{ patientRow.Name }}</span>
          </el-col>
          <el-col :span="12">
            <span>性别：</span>
            <span>{{ personInfo.SEX }}</span>
          </el-col>
          <el-col :span="12">
            <span>年龄：</span>
            <span>{{ patientRow.AgeYear }}岁</span>
          </el-col>
          <el-col :span="12">
            <span>身高/体重：</span>
            <span
              >{{ patientDetail.Height }}cm/{{ patientDetail.Height }}kg</span
            >
          </el-col>
          <el-col :span="12">
            <span>联系电话：</span>
            <span>{{ patientRow.PhoneNo }}</span>
          </el-col>
          <el-col :span="12">
            <span>单位或地址：</span>
            <span>{{ patientDetail.Address }}</span>
          </el-col>
          <el-col :span="24">
            <span>主诉：</span>
            <span>{{ patientDetail.Complaints }}</span>
          </el-col>
          <el-col :span="24">
            <span>现病史：</span>
            <span>{{ patientDetail.PresentHis }}</span>
          </el-col>
          <el-col :span="24">
            <span>既往史：</span>
            <span>{{ patientDetail.PastHistory }}</span>
          </el-col>
          <el-col :span="24">
            <span>过敏史：</span>
            <span>{{ patientDetail.AllergicHis }}</span>
          </el-col>
          <el-col :span="24">
            <span>生命体征：</span>
            <span></span>
          </el-col>
          <el-col :span="24">
            <span>辅助检查：</span>
            <span></span>
          </el-col>
          <el-col :span="24">
            <span>诊断：</span>
            <span>{{ patientDetail.Diagnosis || patientDetail.TCM }}</span>
          </el-col>
          <el-col :span="24">
            <span>医嘱：</span>
            <span></span>
          </el-col>
          <el-col :span="24">
            <span>健康教育：</span>
            <span></span>
          </el-col>
          <el-col :span="24">
            <span>处理意见：</span>
            <span>{{ patientDetail.MedicalContent }}</span>
          </el-col>
          <el-col :span="24">
            <span>病历：</span>
            <span>
              <el-button
                size="mini"
                type="primary"
                plain
                v-for="(v, index) in ihDataList"
                :key="index"
                @click="viewFilePDFDetail({ EmrId: v.EmrId }, 4)"
              >
                {{ v.EmrName }}
              </el-button></span
            >
          </el-col>
          <el-col :span="24">
            <span>处方：</span>
            <span>
              <el-button
                size="mini"
                type="primary"
                plain
                v-for="(item, index) in prescriptionList"
                :key="index"
                @click="viewPrescriptionDetail(item.PrescriptionId, 4)"
              >
                {{ item.PrescriptionId }}
              </el-button>
            </span>
          </el-col>
          <el-col :span="12">
            <span>就诊日期：</span>
            <span>{{ patientDetail.VisitDate }}</span>
          </el-col>
          <el-col :span="12">
            <span>医生签名：</span>
            <span>{{ patientDetail.DoctName }}</span>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <!-- 就诊文件详情列表 -->
    <el-dialog
      custom-class="patient-detail-dialog"
      :visible.sync="inHospitalDetailDialog"
    >
      <el-table
        class="l-table"
        :data="ihDataList"
        border
        max-height="300"
        highlight-current-row
      >
        <el-table-column prop="EmrName" label="文件名称">
          <template slot-scope="scope">
            <span>{{ scope.row.EmrName || "-" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="EmrType" label="文件类别">
          <template slot-scope="scope">
            <span>{{ scope.row.EmrType || "-" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="OperDate" label="操作时间">
          <template slot-scope="scope">
            <span>{{ scope.row.OperDate || "-" }} </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="70" fixed="right">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              @click="viewFilePDFDetail(scope.row)"
              >详情</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!--打开自画处方签弹框 start-->
    <his-prescription-dialog
      ref="preDialog"
      :has-save="false"
    ></his-prescription-dialog>
    <!--打开pdf弹框 start-->
  </div>
</template>

<script>
import {
  authLogin,
  pub_GetPatienArchiveByIdCardNo,
  pub_QueryClinicPatientInfo,
  pub_QueryPrescriptionList_v2,
  pub_QueryOutRecordInfo,
  pub_QueryPrescriptionDetail,
  pub_QueryInHospitalRecordDetail,
  pub_QueryInHospitalRecordList,
  pub_QueryInpatientInfo
} from "@/api";
// import { post } from 'axios';
import Axios from "axios";
import Global from "@/utils/global";
import hisPrescriptionDialog from "@/components/chatroom/view-his-prescription";
import { getStore } from "@/utils/storage";
export default {
  props: {
    info: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    hisPrescriptionDialog
  },
  data() {
    return {
      hisDialog: false,
      activeName: "1",
      dataList: [], //列表数据
      dataPage: {
        //列表分页
        total: 0,
        pageNum: 1,
        pageSize: 50
      },
      hisToken: "",
      patient: {
        cardId: "",
        cardType: ""
      },
      cardList: [],
      cardTypeList: [],
      personInfo: {}, //就诊人信息
      patientDetailDialog: false,
      patientDetail: {},
      patientRow: {},
      prescriptionList: [],
      prescriptionDetail: [],
      inHospitalRow: {},
      inHospitalDetailDialog: false,
      ihDataList: [],
      prescriptionId: 0
    };
  },

  watch: {
    async hisDialog(n) {
      if (n) {
        await this.authLogin();
        this.init();
      }
    }
  },
  created() {},
  methods: {
    openDialog() {
      this.hisDialog = true;
    },
    closeDialog() {
      this.hisDialog = false;
    },
    handleActive(v) {
      if (this.activeName == 1) {
        this.pub_QueryClinicPatientInfo();
      } else if (this.activeName == 3) {
        this.pub_QueryInpatientInfo();
      }
    },
    changePage(val) {
      this.dataPage.pageNum = val;
      if (this.activeName == 1) {
        this.pub_QueryClinicPatientInfo();
      } else if (this.activeName == 3) {
        this.pub_QueryInpatientInfo();
      }
    },
    async authLogin() {
      let res = await authLogin();
      this.hisToken = res.msg;
    },
    async pub_QueryClinicPatientInfo() {
      let res = await pub_QueryClinicPatientInfo(
        {
          CardType: 1,
          CardId: this.personInfo.CARDID,
          StartTime: this.getLast6MonthsDates().past,
          EndTime: this.getLast6MonthsDates().now,
          PageNum: this.dataPage.pageNum,
          PageSize: this.dataPage.pageSize
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.dataList = res.data;
      this.dataPage.total = Number(res.data[0].TotalCount);
    },
    async pub_QueryPrescriptionList_v2() {
      let res = await pub_QueryPrescriptionList_v2(
        {
          CardId: this.patientRow.CardId,
          StartTime: this.getLast6MonthsDates().past,
          EndTime: this.getLast6MonthsDates().now,
          PageNum: 1,
          PageSize: 10,
          VisitId: this.patientRow.VisitId
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.prescriptionList = res.data;
    },
    async pub_QueryOutRecordInfo() {
      let res = await pub_QueryOutRecordInfo(
        {
          CardId: this.patientRow.CardId,
          VisitId: this.patientRow.VisitId
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.patientDetail = res.data ? res.data[0] : {};
      this.pub_QueryInHospitalRecordList();
    },
    async pub_QueryPrescriptionDetail(id) {
      this.prescriptionId = id;
      let res = await pub_QueryPrescriptionDetail(
        {
          PrescriptionId: id
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.prescriptionDetail = res.data;
    },
    async getIdCard() {
      let res = await pub_GetPatienArchiveByIdCardNo(
        {
          IdCardNo: this.info.patientIdcard
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.personInfo = res.data;
    },
    async init() {
      await this.getIdCard();
      this.pub_QueryClinicPatientInfo();
    },
    changePage() {
      this.pub_QueryClinicPatientInfo();
    },
    viewDetail(row) {
      this.patientDetailDialog = true;
      this.patientRow = row;
      this.pub_QueryOutRecordInfo();
      this.pub_QueryPrescriptionList_v2();
    },

    async viewPrescriptionDetail(id) {
      await this.pub_QueryPrescriptionDetail(id);
      this.$refs.preDialog &&
        this.$refs.preDialog.open({
          patientRow: this.patientRow,
          patientDetail: this.patientDetail,
          prescriptionDetail: this.prescriptionDetail,
          personInfo: this.personInfo,
          prescriptionId: id
        });
    },
    async pub_QueryInpatientInfo() {
      let res = await pub_QueryInpatientInfo(
        {
          CardId: this.personInfo.CARDID,
          StartTime: this.getLast6MonthsDates().past,
          EndTime: this.getLast6MonthsDates().now,
          PageNum: this.dataPage.pageNum,
          PageSize: this.dataPage.pageSize
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.dataList = res.data;
      this.dataPage.total = Number(res.data[0].TotalCount) || 0;
    },
    viewFileDetail(row) {
      this.inHospitalRow = row;
      this.inHospitalDetailDialog = true;
      this.pub_QueryInHospitalRecordList();
    },
    async pub_QueryInHospitalRecordList() {
      let res = await pub_QueryInHospitalRecordList(
        {
          CardId: this.personInfo.CARDID,
          MedicalId:
            this.activeName == 1
              ? this.patientRow.VisitId
              : Number(this.inHospitalRow.AdmissionId),
          MedicalType: this.activeName == 1 ? 1 : 2
        },
        {
          hasHisToken: true,
          hisToken: this.hisToken
        }
      );
      this.ihDataList = res.data;
    },
    async viewFilePDFDetail(row) {
      let base = Global.getBaseUrl();
      let res = await Axios({
        method: "post",
        url: `${base}/web/renan_his/api/InpatientBusiness/Pub_QueryInHospitalRecordDetail`,
        data: {
          DocumentId: this.activeName == 1 ? "1_" + row.EmrId : "2_" + row.EmrId
        },
        headers: {
          hasHisToken: true,
          hisToken: this.hisToken,
          webToken: getStore("accessToken")
        },
        responseType: "arraybuffer"
      });
      let pdfData = new Uint8Array(res.data);
      let pdfBlob = new Blob([pdfData], { type: "application/pdf" });
      // 创建URL指向该Blob对象
      let pdfUrl = URL.createObjectURL(pdfBlob);

      // 现在可以使用pdfUrl来访问或者展示PDF，例如：
      // 1. 插入到页面作为链接
      let pdfLink = document.createElement("a");
      pdfLink.href = pdfUrl;
      pdfLink.download = "downloaded-pdf.pdf";
      pdfLink.textContent = "下载PDF";
      document.body.appendChild(pdfLink);

      // 2. 在新窗口打开PDF
      window.open(pdfUrl);

      // 3. 作为iframe嵌入
      let iframe = document.createElement("iframe");
      iframe.style = "display:none;";
      iframe.src = pdfUrl;
      document.body.appendChild(iframe);

      // 请记得在不需要的时候释放掉创建的URL
      window.addEventListener("beforeunload", () => {
        URL.revokeObjectURL(pdfUrl);
      });
    },
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0)
        byteString = atob(base64Data.split(",")[1]);
      //base64 解码
      else {
        byteString = unescape(base64Data.split(",")[1]);
      }
      var mimeString = base64Data
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ia = new Uint8Array(byteString.length); //创建视图
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      var blob = new Blob([ia], {
        type: mimeString
      });
      return blob;
    },
    showAgreementBook(data) {
      var blob = this.dataURItoBlob(data);
      // for IE 兼容IE，弹出用户操作框，用户可自行选择下载或打开
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob);
      } else {
        let fileURL = URL.createObjectURL(blob);
        // 会生成类似 blob:XXX/XXXXX-XXXXX-XXXXX-XXXXX-526fc462d662 地址，并在新标签页打开，可下载
        window.open(fileURL);
      }
    },
    //获得当前时间至以前6个月
    getLast6MonthsDates() {
      let time = new Date();
      time.setTime(time.getTime());
      let now =
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
      let monthNum = 6; //要减的月数(6)自己定义
      let dateArr = now.split("-"); //s2当前时间
      let year = dateArr[0]; //获取当前日期的年份
      let month = dateArr[1]; //获取当前日期的月份
      let day = dateArr[2]; //获取当前日期的日
      let days = new Date(year, month, 0);
      days = days.getDate(); //获取当前日期中月的天数
      let year2 = year;
      let month2 = parseInt(month) - monthNum;
      if (month2 <= 0) {
        year2 =
          parseInt(year2) -
          parseInt(month2 / 12 == 0 ? 1 : parseInt(month2) / 12);
        month2 = 12 - (Math.abs(month2) % 12);
      }
      let day2 = day;
      let days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = "0" + month2;
      }
      let past = year2 + "-" + month2 + "-" + day2;
      return {
        past: past + " 00:00:00",
        now: now + " 23:59:59"
      };
    }
  }
};
</script>

<style lang="scss">
.patient-detail-dialog {
  /* width: 400px !important; */
}
</style>
